<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录功能测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .test-section {
            background: white;
            margin: 20px 0;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .test-section h3 {
            color: #333;
            border-bottom: 2px solid #4e5eff;
            padding-bottom: 10px;
        }
        .form-group {
            margin: 15px 0;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .form-group input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .btn {
            background-color: #4e5eff;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        .btn:hover {
            background-color: #3a4acc;
        }
        .btn:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        .result {
            margin-top: 15px;
            padding: 10px;
            border-radius: 4px;
            white-space: pre-wrap;
            font-family: monospace;
            font-size: 12px;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .info {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        .status-info {
            background-color: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <h1>Asurada 登录功能测试</h1>
    
    <div class="status-info">
        <h4>测试说明</h4>
        <p>此页面用于测试前端登录功能的完整性，包括两步登录、令牌管理、用户状态等功能。</p>
        <p><strong>注意：</strong>需要后端服务运行在 http://localhost:8082</p>
    </div>

    <!-- 登录状态检查 -->
    <div class="test-section">
        <h3>1. 登录状态检查</h3>
        <button class="btn" onclick="checkLoginStatus()">检查当前登录状态</button>
        <button class="btn" onclick="getCurrentUser()">获取当前用户信息</button>
        <div id="status-result" class="result info" style="display: none;"></div>
    </div>

    <!-- 两步登录测试 -->
    <div class="test-section">
        <h3>2. 两步登录测试</h3>
        <div class="form-group">
            <label for="phone">手机号:</label>
            <input type="text" id="phone" value="13800138000" placeholder="请输入手机号">
        </div>
        <div class="form-group">
            <label for="password">密码:</label>
            <input type="password" id="password" value="123456" placeholder="请输入密码">
        </div>
        <button class="btn" onclick="testLogin()">执行两步登录</button>
        <button class="btn" onclick="testGetAuthCode()">仅获取授权码</button>
        <button class="btn" onclick="testGetToken()">仅获取令牌</button>
        <div id="login-result" class="result" style="display: none;"></div>
    </div>

    <!-- 验证码登录测试 -->
    <div class="test-section">
        <h3>3. 验证码登录测试</h3>
        <div class="form-group">
            <label for="code-phone">手机号:</label>
            <input type="text" id="code-phone" value="13800138000" placeholder="请输入手机号">
        </div>
        <div class="form-group">
            <label for="verification-code">验证码:</label>
            <input type="text" id="verification-code" value="123456" placeholder="请输入验证码">
        </div>
        <button class="btn" onclick="sendVerificationCode()">发送验证码</button>
        <button class="btn" onclick="loginByCode()">验证码登录</button>
        <div id="code-result" class="result" style="display: none;"></div>
    </div>

    <!-- 令牌管理测试 -->
    <div class="test-section">
        <h3>4. 令牌管理测试</h3>
        <button class="btn" onclick="verifyToken()">验证当前令牌</button>
        <button class="btn" onclick="refreshToken()">刷新令牌</button>
        <button class="btn" onclick="clearTokens()">清除所有令牌</button>
        <div id="token-result" class="result" style="display: none;"></div>
    </div>

    <!-- 登出测试 -->
    <div class="test-section">
        <h3>5. 登出测试</h3>
        <button class="btn" onclick="logout()">用户登出</button>
        <div id="logout-result" class="result" style="display: none;"></div>
    </div>

    <script>
        // 模拟 uni-app 环境
        const uni = {
            request: (options) => {
                return fetch(options.url, {
                    method: options.method || 'GET',
                    headers: options.header || {},
                    body: options.data ? JSON.stringify(options.data) : undefined,
                    credentials: 'include' // 支持Cookie
                }).then(response => {
                    return response.json().then(data => {
                        options.success({
                            statusCode: response.status,
                            data: data
                        });
                    }).catch(err => {
                        options.fail(err);
                    });
                }).catch(err => {
                    options.fail(err);
                });
            },
            showLoading: (options) => console.log('Loading:', options.title),
            hideLoading: () => console.log('Hide loading'),
            showToast: (options) => console.log('Toast:', options.title),
            getStorageSync: (key) => localStorage.getItem(key),
            setStorageSync: (key, value) => localStorage.setItem(key, typeof value === 'object' ? JSON.stringify(value) : value),
            removeStorageSync: (key) => localStorage.removeItem(key)
        };

        // 配置
        const API_BASE_URL = 'http://localhost:8082';
        const API_PATHS = {
            LOGIN: '/asurada/login',
            TOKEN: '/asurada/token',
            LOGOUT: '/asurada/logout',
            REFRESH_TOKEN: '/asurada/refresh',
            VERIFY_TOKEN: '/asurada/verify',
            CHECK_LOGIN_STATUS: '/asurada/status',
            LOGIN_BY_CODE: '/asurada/loginByPhoneAndCode',
            SEND_SMS: '/asurada/sendPhoneCode'
        };

        // API 请求函数
        function apiRequest(url, method = 'GET', data = null) {
            return new Promise((resolve, reject) => {
                const token = localStorage.getItem('asurada_user_token');
                const headers = {
                    'Content-Type': 'application/json'
                };
                
                if (token) {
                    headers['Authorization'] = `Bearer ${token}`;
                }

                uni.request({
                    url: API_BASE_URL + url,
                    method: method,
                    data: data,
                    header: headers,
                    success: (res) => {
                        if (res.statusCode === 200) {
                            resolve(res.data);
                        } else {
                            reject(new Error(`HTTP ${res.statusCode}`));
                        }
                    },
                    fail: (err) => {
                        reject(err);
                    }
                });
            });
        }

        // 显示结果
        function showResult(elementId, result, isError = false) {
            const element = document.getElementById(elementId);
            element.style.display = 'block';
            element.className = `result ${isError ? 'error' : 'success'}`;
            element.textContent = typeof result === 'object' ? JSON.stringify(result, null, 2) : result;
        }

        // 1. 检查登录状态
        async function checkLoginStatus() {
            try {
                const result = await apiRequest(API_PATHS.CHECK_LOGIN_STATUS);
                showResult('status-result', `登录状态检查结果:\n${JSON.stringify(result, null, 2)}`);
            } catch (error) {
                showResult('status-result', `检查登录状态失败:\n${error.message}`, true);
            }
        }

        async function getCurrentUser() {
            try {
                const token = localStorage.getItem('asurada_user_token');
                const userInfo = localStorage.getItem('asurada_user_info');
                const result = {
                    hasToken: !!token,
                    token: token ? token.substring(0, 20) + '...' : null,
                    userInfo: userInfo ? JSON.parse(userInfo) : null
                };
                showResult('status-result', `当前用户信息:\n${JSON.stringify(result, null, 2)}`);
            } catch (error) {
                showResult('status-result', `获取用户信息失败:\n${error.message}`, true);
            }
        }

        // 2. 两步登录测试
        async function testLogin() {
            const phone = document.getElementById('phone').value;
            const password = document.getElementById('password').value;
            
            try {
                // 第一步：获取授权码
                showResult('login-result', '第一步：获取登录授权码...');
                const authResult = await apiRequest(API_PATHS.LOGIN, 'POST', {
                    account: phone,
                    password: password
                });
                
                if (authResult.code === 200) {
                    showResult('login-result', `第一步成功:\n${JSON.stringify(authResult, null, 2)}\n\n第二步：获取登录令牌...`);
                    
                    // 第二步：获取令牌
                    const tokenResult = await apiRequest(API_PATHS.TOKEN, 'POST', {
                        account: phone,
                        password: password
                    });
                    
                    if (tokenResult.code === 200) {
                        // 保存令牌
                        if (tokenResult.data && tokenResult.data.accessToken) {
                            localStorage.setItem('asurada_user_token', tokenResult.data.accessToken);
                            localStorage.setItem('asurada_login_time', Date.now().toString());
                        }
                        
                        showResult('login-result', `两步登录成功:\n第一步: ${JSON.stringify(authResult, null, 2)}\n\n第二步: ${JSON.stringify(tokenResult, null, 2)}`);
                    } else {
                        showResult('login-result', `第二步失败:\n${JSON.stringify(tokenResult, null, 2)}`, true);
                    }
                } else {
                    showResult('login-result', `第一步失败:\n${JSON.stringify(authResult, null, 2)}`, true);
                }
            } catch (error) {
                showResult('login-result', `登录过程出错:\n${error.message}`, true);
            }
        }

        async function testGetAuthCode() {
            const phone = document.getElementById('phone').value;
            const password = document.getElementById('password').value;
            
            try {
                const result = await apiRequest(API_PATHS.LOGIN, 'POST', {
                    account: phone,
                    password: password
                });
                showResult('login-result', `获取授权码结果:\n${JSON.stringify(result, null, 2)}`);
            } catch (error) {
                showResult('login-result', `获取授权码失败:\n${error.message}`, true);
            }
        }

        async function testGetToken() {
            const phone = document.getElementById('phone').value;
            const password = document.getElementById('password').value;
            
            try {
                const result = await apiRequest(API_PATHS.TOKEN, 'POST', {
                    account: phone,
                    password: password
                });
                
                if (result.code === 200 && result.data && result.data.accessToken) {
                    localStorage.setItem('asurada_user_token', result.data.accessToken);
                }
                
                showResult('login-result', `获取令牌结果:\n${JSON.stringify(result, null, 2)}`);
            } catch (error) {
                showResult('login-result', `获取令牌失败:\n${error.message}`, true);
            }
        }

        // 3. 验证码登录测试
        async function sendVerificationCode() {
            const phone = document.getElementById('code-phone').value;
            
            try {
                const result = await apiRequest(`${API_PATHS.SEND_SMS}?phone=${phone}`);
                showResult('code-result', `发送验证码结果:\n${JSON.stringify(result, null, 2)}`);
            } catch (error) {
                showResult('code-result', `发送验证码失败:\n${error.message}`, true);
            }
        }

        async function loginByCode() {
            const phone = document.getElementById('code-phone').value;
            const code = document.getElementById('verification-code').value;
            
            try {
                const result = await apiRequest(API_PATHS.LOGIN_BY_CODE, 'POST', {
                    phone: phone,
                    code: code
                });
                
                if (result.code === 200 && result.data && result.data.token) {
                    localStorage.setItem('asurada_user_token', result.data.token);
                }
                
                showResult('code-result', `验证码登录结果:\n${JSON.stringify(result, null, 2)}`);
            } catch (error) {
                showResult('code-result', `验证码登录失败:\n${error.message}`, true);
            }
        }

        // 4. 令牌管理测试
        async function verifyToken() {
            try {
                const result = await apiRequest(API_PATHS.VERIFY_TOKEN);
                showResult('token-result', `验证令牌结果:\n${JSON.stringify(result, null, 2)}`);
            } catch (error) {
                showResult('token-result', `验证令牌失败:\n${error.message}`, true);
            }
        }

        async function refreshToken() {
            try {
                const result = await apiRequest(API_PATHS.REFRESH_TOKEN, 'POST');
                
                if (result.code === 200 && result.data && result.data.accessToken) {
                    localStorage.setItem('asurada_user_token', result.data.accessToken);
                }
                
                showResult('token-result', `刷新令牌结果:\n${JSON.stringify(result, null, 2)}`);
            } catch (error) {
                showResult('token-result', `刷新令牌失败:\n${error.message}`, true);
            }
        }

        function clearTokens() {
            localStorage.removeItem('asurada_user_token');
            localStorage.removeItem('asurada_user_info');
            localStorage.removeItem('asurada_login_time');
            localStorage.removeItem('asurada_refresh_token');
            localStorage.removeItem('asurada_im_access_token');
            localStorage.removeItem('asurada_im_session_token');
            
            showResult('token-result', '所有令牌已清除');
        }

        // 5. 登出测试
        async function logout() {
            try {
                const result = await apiRequest(API_PATHS.LOGOUT, 'POST');
                
                // 清除本地存储
                clearTokens();
                
                showResult('logout-result', `登出结果:\n${JSON.stringify(result, null, 2)}`);
            } catch (error) {
                showResult('logout-result', `登出失败:\n${error.message}`, true);
            }
        }

        // 页面加载时检查状态
        window.onload = function() {
            checkLoginStatus();
        };
    </script>
</body>
</html>